load Table6Data;
for cntry = [55 50 51]
    switch cntry
        case 55, ctype = 1;
        case 50, ctype = 2; 
        case 51, ctype = 3;
    end
    Betas = Slopes(:,:,ctype);
    
    AllY = []; AllX = [];
    Numer = zeros(1,3); Denom = 0; MSE = NaN(T,3); MAE = NaN(T,3);
    DM = NaN(T,2);
    for t = THalf+1:T
        Y = Return(:,t);
        X = [Return11(:,t-2) squeeze(XVARS(:,t-1,1:7)) MV(:,t-1)];
        idx = isfinite(Y) & all(isfinite(X),2) & CountryRegionDummy(:,cntry) & ~IsREIT & ~IsMicro(:,t-2,cntry);
        if sum(idx)>MinStocks
            if WinsorizeYRet 
                y = winsorize(Y(idx),WinsorLevelY);
            else
                y = Y(idx);
            end
            x = winsorize(X(idx,:),WinsorLevelX);
            
            % neutralize country effects
            K = size(X,2);
            for cc = 1:49
                idx_cc = CountryRegionDummy(idx,cc);
                if sum(idx_cc) >= 1
                    for k = 1:K
                        x(idx_cc,k) = x(idx_cc,k) - mean(x(idx_cc,k),'omitnan');
                    end
                end
            end
            
            xs = standardize(x);
            % convert to residual analyst
            ytemp = xs(:,4); xtemp = [ones(sum(idx),1) xs(:,9)];
            xs(:,4) = ytemp - xtemp*(xtemp\ytemp);
            
            xs2 = [xs(:,1) repmat(xs(:,1),1,7).*xs(:,2:8) xs(:,2:8)];
            xx = [xs2 ones(length(y),1)];
            
            if any(sum(isfinite(xx))==0); continue; end
            if rank(xx) == size(xx,2)
                err = y - xx*Betas;
                Numer = Numer + sum(err.^2);
                Denom = Denom + sum(y.^2);
                DM(t,:) = [mean(err(:,1).^2 - err(:,2).^2) mean(err(:,1).^2 - err(:,3).^2)];
                MSE(t,:) = mean(err.^2);
                MAE(t,:) = mean(abs(err));
            end
        end
    end
    
    D = [100*(1 - Numer/Denom); nanmean(MSE); nanmean(MAE)];
    if cntry == 55
        writematrix(D,FileName, 'Sheet', SheetName, 'Range','b20:d22', 'AutoFitWidth',false);
    elseif cntry == 50
        writematrix(D,FileName, 'Sheet', SheetName, 'Range','f20:h22', 'AutoFitWidth',false);
    elseif cntry == 51
        writematrix(D,FileName, 'Sheet', SheetName, 'Range','j20:l22', 'AutoFitWidth',false);
    end
    mean(DM,'omitnan')./std(DM,'omitnan')
end
